package com.pro01.backend.service;

import com.pro01.backend.mapper.EmailVerificationMapper;
import com.pro01.backend.pojo.EmailVerification;
import jakarta.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private EmailVerificationMapper emailVerificationMapper;

    public boolean sendEmailCode(String email) {
        // 生成6位验证码
        String code = String.valueOf(new Random().nextInt(900000) + 100000);

        try {
            // 1. 存入数据库
            EmailVerification verification = new EmailVerification();
            verification.setEmail(email);
            verification.setCode(code);
            emailVerificationMapper.saveEmailCode(verification);

            // 创建 MIME 消息
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

            // 发送人必须和 SMTP 认证用户一致
            helper.setFrom("pianodrum@163.com"); // 这里必须和 SMTP 认证的邮箱一致
            helper.setTo(email);
            helper.setSubject("PT站 注册验证码");
            helper.setText("您的验证码是：" + code + "，有效期10分钟。");

            // 发送邮件
            mailSender.send(mimeMessage);

            return true;
        } catch (Exception e) {
            e.printStackTrace(); // 打印详细错误
            return false;
        }
    }

}
